package com.yonyou.cyxdms.sysAuth.service.service.authorization;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.authorization.AuthorizationDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.*;
import com.yonyou.cyxdms.sysAuth.service.mapper.*;
import com.yonyou.cyxdms.sysAuth.service.utill.MD5Util;
import com.yonyou.cyxdms.sysAuth.service.vo.authorization.AuthorizationVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author ：quankk
 * @date ：2019/7/18 16:39
 * @description：
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AuthorizationServiceImpl implements AuthorizationService {

    // 定义日志接口
    private static final Logger logger = LoggerFactory.getLogger(AuthorizationServiceImpl.class);

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TcUserMapper tcUserMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private UserOrgPositionMapper userOrgPositionMapper;

    /**
     * @author ：quankk
     * @date ：2019/7/18 16:57
     * @description：加载授权主界面
     */
    @Override
    public IPage<AuthorizationVO> queryAuthorization(Page<AuthorizationVO> page, Map<String, String> param) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        param.put("appId", loginInfoDto.getAppId());
        param.put("dealerCode", loginInfoDto.getOwnerCode());
        List<AuthorizationVO> list = empMapper.queryAuthorization(page, param);
        if (!CommonUtils.isNullOrEmpty(list)) {
            list.stream().forEach(authorizationVO -> {
                List<String> roleList = empMapper.selectPositionName(authorizationVO.getUserId());
                StringBuilder sb3 = new StringBuilder();
                if (!CommonUtils.isNullOrEmpty(roleList)) {
                    roleList.stream().forEach(role -> {
                        sb3.append(role).append(",");
                    });
                    authorizationVO.setEmpPosition(StringUtils.isNullOrEmpty(sb3.toString()) ? sb3.substring(0, sb3.length() - 1) : null);
                }
            });
        }
        page.setRecords(list);
        //判断分页是否超过最大分页，设置为第一页数
        if (page.getCurrent() > page.getPages()) {
            Map<String, String> param2 = param;
            param2.remove("pageNum");
            param2.put("pageNum", "1");
            Page<AuthorizationVO> page2 = new Page(1, page.getSize());
            List<AuthorizationVO> list2 = empMapper.queryAuthorization2(page2, param2);
            if (!CommonUtils.isNullOrEmpty(list2)) {
                list2.stream().forEach(authorizationVO -> {
                    List<String> roleList = empMapper.selectPositionName(authorizationVO.getUserId());
                    StringBuilder sb3 = new StringBuilder();
                    if (!CommonUtils.isNullOrEmpty(roleList)) {
                        roleList.stream().forEach(role -> {
                            sb3.append(role).append(",");
                        });
                        authorizationVO.setEmpPosition(StringUtils.isNullOrEmpty(sb3.toString()) ? sb3.substring(0, sb3.length() - 1) : null);
                    }
                });
            }
            page2.setRecords(list2);
            return page2;
        }
        return page;
    }

    /**
     * @author ：quankk
     * @date ：2019/7/18 18:23
     * @description：授权信息获取
     */
    @Override
    public List<Map> getRoleById(Integer id) {
        return empMapper.getRoleById(id);
    }

    /**
     * @author ：quankk
     * @date ：2019/7/18 18:32
     * @description：vue停用
     */
    @Override
    public void vuePosition(Integer id) {
        LambdaQueryWrapper<UserPO> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(UserPO::getEmpId, id);
        List<UserPO> userpolist = userMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(userpolist)) {
            userpolist.stream().forEach(userPo -> {
                userPo.setStopDate(LocalDateTime.now());
                userPo.setUserStatus(10031002);
                userMapper.updateById(userPo);
            });
        }
    }

    /**
     * @author ：quankk
     * @date ：2019/7/18 19:03
     * @description：新增授权
     */
    @Override
    public void addAuthorization(AuthorizationDTO atdto) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String[] ids = atdto.getIds().split(",");
        Integer cuserId = null;
        Integer employId;
        if (!StringUtils.isNullOrEmpty(atdto.getEmployeeId())) {
            employId = atdto.getEmployeeId();
            LambdaQueryWrapper<UserPO> queryWrapper = new QueryWrapper().lambda();
            queryWrapper.eq(UserPO::getEmpId, employId);
            //检查账号是否存在
            //根据员工id查询账号信息
            UserPO userInfoMap = userMapper.selectOne(queryWrapper);
            //如果账号信息不存在或者账号不存在
            if (ObjectUtils.isEmpty(userInfoMap) || StringUtils.isNullOrEmpty(userInfoMap.getUserCode())) {
                LambdaQueryWrapper<TcUserPO> lambdaQueryWrapper = new QueryWrapper().lambda();
                lambdaQueryWrapper.eq(TcUserPO::getUserCode, atdto.getUserCode())
                        .eq(TcUserPO::getAppId, loginInfoDto.getAppId())
                        .eq(TcUserPO::getOwnerCode, loginInfoDto.getOwnerCode());
                List<TcUserPO> user = tcUserMapper.selectList(lambdaQueryWrapper);
                if (!CommonUtils.isNullOrEmpty(user)) {
                    throw new ServiceBizException("账号已存在!");
                }
                //回写tm_emp、tm_employee
                EmployeePO employeepo = employeeMapper.selectById(employId);
                // employeePO.setDateType(ManageDictCodeConstants.DATA_TYPE_BY_GROUP);
                employeeMapper.updateById(employeepo);
                EmpPo empPo = empMapper.selectById(employeepo.getEmpId());
                LambdaQueryWrapper<EmpPo> empPoLambdaQueryWrapper = new QueryWrapper().lambda();
                empPoLambdaQueryWrapper.eq(EmpPo::getUserCode, atdto.getUserCode())
                        .eq(EmpPo::getAppId, loginInfoDto.getAppId())
                        .eq(EmpPo::getOpenId, loginInfoDto.getOwnerCode());
                List<EmpPo> empPoList = empMapper.selectList(empPoLambdaQueryWrapper);
                if (empPoList.size() != 0) {
                    throw new ServiceBizException("该账号已存在");
                }
                empPo.setUserCode(atdto.getUserCode());
                //     empPO.setLockFlag(ManageDictCodeConstants.STATUS_IS_NOT);
                //     empPO.setFailureNum(0);
                String encryptedPwd = MD5Util.getEncryptedPwd(ManageDictCodeConstants.LOGIN_PW);
                //     empPO.setPassword(PasswordMD5);
                empMapper.updateById(empPo);
                // 更新tc_user信息
                TcUserPO tcuserpo = new TcUserPO();
                tcuserpo.setOwnerCode(loginInfoDto.getOwnerCode());
                //tcUserPO.setGroupCode(loginInfoDto.getGroupCode());
                tcuserpo.setAppId(loginInfoDto.getAppId());
                tcuserpo.setUserCode(atdto.getUserCode());
                tcuserpo.setUserType(1);
                tcUserMapper.insert(tcuserpo);
            } else {
                EmployeePO employeepo = employeeMapper.selectById(employId);
                EmpPo empPo = empMapper.selectById(employeepo.getEmpId());
                empPo.setUserStatus(atdto.getUserStatus());
                empMapper.updateById(empPo);
            }
            for (int i = 0; i < ids.length; i++) {
                //如果是第一次授权，则创建用户信息，再把职位挂在用户信息下
                Integer employeeId = Integer.parseInt(ids[i]);
                Integer userId = 0;
                List<Map> aa = empMapper.hasUser(employeeId, atdto.getType());
                if (CommonUtils.isNullOrEmpty(aa)) {
                    UserPO userpo = new UserPO();
                    userpo.setEmpId(employeeId);//??要不要存usercode
                    userpo.setUserStatus(10031001);
                    userMapper.insert(userpo);
                    userId = userpo.getUserId();
                } else {
                    userId = Integer.parseInt(aa.get(0).get("USER_ID").toString());
                }
                LambdaQueryWrapper<UserOrgPositionPO> lambdaQueryWrapper = new QueryWrapper().lambda();
                lambdaQueryWrapper.eq(UserOrgPositionPO::getUserId, userId);
                List<UserOrgPositionPO> userorgpositionpolist = userOrgPositionMapper.selectList(lambdaQueryWrapper);
                for (int k = 0; k < userorgpositionpolist.size(); k++) {
                    Integer poId = userorgpositionpolist.get(k).getOrgPositionId();
                    LambdaQueryWrapper<UserOrgPositionPO> poIdLambdaQueryWrapper = new QueryWrapper().lambda();
                    poIdLambdaQueryWrapper.eq(UserOrgPositionPO::getUserId, userId).eq(UserOrgPositionPO::getOrgPositionId, poId);
                    userOrgPositionMapper.delete(poIdLambdaQueryWrapper);
                }
                for (int j = 0; j < atdto.getAllocatedList().size(); j++) {
                    UserOrgPositionPO userorgpositionpo = new UserOrgPositionPO();
                    userorgpositionpo.setUserId(userId);
                    userorgpositionpo.setOrgPositionId(atdto.getAllocatedList().get(j).getPositionId());
                    userOrgPositionMapper.insert(userorgpositionpo);
                }
                if (!StringUtils.isNullOrEmpty(employId)) {
                    cuserId = userId;
                }
            }
            if (!StringUtils.isNullOrEmpty(employId)) {
                UserPO userpo = userMapper.selectById(cuserId);
                userpo.setUserCode(atdto.getUserCode());
                userpo.setUserStatus(atdto.getUserStatus());
                userMapper.updateById(userpo);
            }
        }
    }

}
